library(MASS)
data("Boston")
There are many data sets already loaded in R or included in the package installations. In this exercise we will practise our analysis on a data set called “Boston” from the “MASS” package. The data set concernes the housing values in the suburbs of Boston. It has 14 varibales with 506 observations, concerning living standards, like accssability and number of rooms.
The description of the variables are:
crim -per capita crime rate by town.
zn -proportion of residential land zoned for lot over 25,000sq.ft.
indus -proportion of non-retail business acres per town.
chas -Charles River dummy variable (=1 if tract bounds river; 0 otherwise).
nox -nitrogen oxides concentration (parts per 10 million).
rm -average number of rooms per dwelling.
age -proportion of owner-occupied units built prior to 1940.
dis -weigthed mean of distances to five Boston employment centres.
rad -index of accessibility to radial highways.
tax -full-value property-tax rate per 10,000$.
ptratio -pupil-teacher ratio by town.
black -1000(Bk-0.63)^2 where Bk is the proportion of blacks by town.
lstat -lower status of the population (percent).
medv -median value of owner-occupied homes in $1000s.
dim(Boston)
## [1] 506 14
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
All the observations of the variables are numerival except for indus and rad, which are integer.
Now, lets have a look at the summary of the distributions of the variables. Here we can see for example, that the mean crime rate is 3.61, whereas the median is 0.25 and the values range between 0.00 and 88.9. The mean of the pupil/teacher ratio is 18.46, which I find surprisingly low.
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
With the following barplots we can get a graphical overview of the distribution of the data withing the variables.
library(ggplot2)
library(tidyr)
gather(Boston) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar()
Using the pairs function we can see how the variables are distributed and derive first assumptions about their relationships to each other. However, there are too many variables to get an overview at one glance.
pairs(Boston)
A better option to investigate the relationship of the variables is the corrolation matrix, or more visual, the corrolation plot. The corrolation matrix shows the correlation coefficient between two variables. In the corolation plot the colour indicates what kind of correlation we have:
red - negative correlation
blue - positive correlation
The size of the cirlce and the intensity of the colour indicate the correlation coefficient.
strong colours - corrolation coefficient is high
light colours - corrolation coefficient is low
The strongest correlation can be found betwenn the index of accessibility to radial highways (rad) and the full-value property-tax rate per 10,000$ (tax) with a correlation coefficient of 0.91. The weighted mean of distances to five Boston employment centres (dis) correlates strongly with age (age), nitrogen oxide concentration (nox) and the proportion of non-retail business acres per town (indus).
library(corrplot)
## corrplot 0.84 loaded
cor_matrix<-cor(Boston)
cor_matrix %>% round(digits=2)
## crim zn indus chas nox rm age dis rad tax
## crim 1.00 -0.20 0.41 -0.06 0.42 -0.22 0.35 -0.38 0.63 0.58
## zn -0.20 1.00 -0.53 -0.04 -0.52 0.31 -0.57 0.66 -0.31 -0.31
## indus 0.41 -0.53 1.00 0.06 0.76 -0.39 0.64 -0.71 0.60 0.72
## chas -0.06 -0.04 0.06 1.00 0.09 0.09 0.09 -0.10 -0.01 -0.04
## nox 0.42 -0.52 0.76 0.09 1.00 -0.30 0.73 -0.77 0.61 0.67
## rm -0.22 0.31 -0.39 0.09 -0.30 1.00 -0.24 0.21 -0.21 -0.29
## age 0.35 -0.57 0.64 0.09 0.73 -0.24 1.00 -0.75 0.46 0.51
## dis -0.38 0.66 -0.71 -0.10 -0.77 0.21 -0.75 1.00 -0.49 -0.53
## rad 0.63 -0.31 0.60 -0.01 0.61 -0.21 0.46 -0.49 1.00 0.91
## tax 0.58 -0.31 0.72 -0.04 0.67 -0.29 0.51 -0.53 0.91 1.00
## ptratio 0.29 -0.39 0.38 -0.12 0.19 -0.36 0.26 -0.23 0.46 0.46
## black -0.39 0.18 -0.36 0.05 -0.38 0.13 -0.27 0.29 -0.44 -0.44
## lstat 0.46 -0.41 0.60 -0.05 0.59 -0.61 0.60 -0.50 0.49 0.54
## medv -0.39 0.36 -0.48 0.18 -0.43 0.70 -0.38 0.25 -0.38 -0.47
## ptratio black lstat medv
## crim 0.29 -0.39 0.46 -0.39
## zn -0.39 0.18 -0.41 0.36
## indus 0.38 -0.36 0.60 -0.48
## chas -0.12 0.05 -0.05 0.18
## nox 0.19 -0.38 0.59 -0.43
## rm -0.36 0.13 -0.61 0.70
## age 0.26 -0.27 0.60 -0.38
## dis -0.23 0.29 -0.50 0.25
## rad 0.46 -0.44 0.49 -0.38
## tax 0.46 -0.44 0.54 -0.47
## ptratio 1.00 -0.18 0.37 -0.51
## black -0.18 1.00 -0.37 0.33
## lstat 0.37 -0.37 1.00 -0.74
## medv -0.51 0.33 -0.74 1.00
corrplot(cor_matrix, method="circle", type = "upper", cl.pos = "b", tl.pos = "d", tl.cex = 0.6)
Now we are standardizing the dataset in order to conduct the linear discriminant analysis.As the data contains only numerical values, we can use the scale() function to standardize the whole dataset. The scaling needs to be done, because the linear discriminant analysis assumes that the variables are normally distributed and the variance of each variable is the same. Bellow we can see the summaries of the scaled data and compare it to the prvious summary. All the variable have the same scale now. The mean for each variable is now 0.
boston_scaled <- scale(Boston)
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
Furthermore we are creating a factor variable for the crime rate. The variable crim describes the per capita crime rate by town. The observations of that variable, derived from the scaled data, are split into four categories on the quantiles (25%). The categories are “low”, “medium low”, “medium high” and “high”. The new variable “crime” is replacing the old variable “crim”.
class(boston_scaled)
## [1] "matrix"
boston_scaled <- as.data.frame(boston_scaled)
bins <- quantile(boston_scaled$crim)
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))
boston_scaled <- dplyr::select(boston_scaled, -crim)
boston_scaled <- data.frame(boston_scaled, crime)
head(boston_scaled)
## zn indus chas nox rm age
## 1 0.2845483 -1.2866362 -0.2723291 -0.1440749 0.4132629 -0.1198948
## 2 -0.4872402 -0.5927944 -0.2723291 -0.7395304 0.1940824 0.3668034
## 3 -0.4872402 -0.5927944 -0.2723291 -0.7395304 1.2814456 -0.2655490
## 4 -0.4872402 -1.3055857 -0.2723291 -0.8344581 1.0152978 -0.8090878
## 5 -0.4872402 -1.3055857 -0.2723291 -0.8344581 1.2273620 -0.5106743
## 6 -0.4872402 -1.3055857 -0.2723291 -0.8344581 0.2068916 -0.3508100
## dis rad tax ptratio black lstat
## 1 0.140075 -0.9818712 -0.6659492 -1.4575580 0.4406159 -1.0744990
## 2 0.556609 -0.8670245 -0.9863534 -0.3027945 0.4406159 -0.4919525
## 3 0.556609 -0.8670245 -0.9863534 -0.3027945 0.3960351 -1.2075324
## 4 1.076671 -0.7521778 -1.1050216 0.1129203 0.4157514 -1.3601708
## 5 1.076671 -0.7521778 -1.1050216 0.1129203 0.4406159 -1.0254866
## 6 1.076671 -0.7521778 -1.1050216 0.1129203 0.4101651 -1.0422909
## medv crime
## 1 0.1595278 low
## 2 -0.1014239 low
## 3 1.3229375 low
## 4 1.1815886 low
## 5 1.4860323 low
## 6 0.6705582 low
Before the linear discriminant analysis we are dividing the dataset into a train and a test set with 80% and respectively 20% of the observations per variable, which are randomly selected.The test set will be used to test how well the predictions of the model fit, i.e. how well it works.
n <- nrow(boston_scaled)
ind <- sample(n, size = n*0.8)
train <- boston_scaled[ind,]
test <- boston_scaled[-ind,]
dim(test)
## [1] 102 14
dim(train)
## [1] 404 14
Now we ar fitting a linear discriminant analysis (LDA) to the training set. Crime is the target varaible and all the other variables are predictors.
lda.fit <- lda(crime ~ ., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2376238 0.2475248 0.2599010 0.2549505
##
## Group means:
## zn indus chas nox rm
## low 0.85110710 -0.8583450 -0.06727176 -0.8673951 0.3974441
## med_low -0.06447162 -0.2820232 -0.11484506 -0.5423483 -0.1095253
## med_high -0.36310067 0.1257442 0.21512144 0.3426453 0.0992397
## high -0.48724019 1.0170891 -0.04298342 1.1098420 -0.4147785
## age dis rad tax ptratio
## low -0.8715904 0.7853022 -0.6851839 -0.7320202 -0.42693157
## med_low -0.3382695 0.3304763 -0.5362660 -0.4309861 -0.04089415
## med_high 0.3759047 -0.3561820 -0.3901372 -0.3214723 -0.31775144
## high 0.8372910 -0.8602190 1.6384176 1.5142626 0.78111358
## black lstat medv
## low 0.3716064 -0.73837072 0.498289313
## med_low 0.3077749 -0.14147242 -0.003675757
## med_high 0.0966462 0.03043213 0.171332747
## high -0.7462361 0.87906009 -0.706194274
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.13531086 0.80664848 -1.02400430
## indus -0.03411545 -0.17154859 0.25803660
## chas -0.07276533 -0.08051101 -0.09090507
## nox 0.44921248 -0.79905986 -1.22133988
## rm -0.09497722 -0.09770782 -0.11783445
## age 0.24655576 -0.34201926 -0.02769297
## dis -0.08403395 -0.41012812 0.37148723
## rad 3.01726570 0.84056638 -0.33819585
## tax -0.05140747 0.04140256 0.87654877
## ptratio 0.13538237 0.06224367 -0.22735308
## black -0.13035241 0.01649606 0.13239933
## lstat 0.24452732 -0.27726740 0.40136597
## medv 0.20113045 -0.42933604 -0.05854317
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9524 0.0366 0.0110
We can draw a LDA biplot to visualize how the data is distributed. Each colour represents a different class and the arrow represent the predictor variable. Length and direction are based on the coefficients and show their impact on the model.
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "orange", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
classes <- as.numeric(train$crime)
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1)
With our trained LDA-model, we can make predictions about new observations for the variable crime. We predict the classes with the LDA model and apply it on the test set. We cross tabulate the results of our predictions with the crime categories from the test set we created earlier. We can see that 72 observations were correctly predicted and 30 were false. That means our training error is about 31.8%
correct_classes<-test$crime
test<-dplyr::select(test, -crime)
lda.pred <- predict(lda.fit, newdata = test)
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 20 9 2 0
## med_low 3 20 3 0
## med_high 0 3 18 0
## high 0 0 0 24
First scale the dataset Boston again and calculate the distances between the observations. For calculating the distances between the obeservations we use the most common, euclidean distance.
#reloading
data(Boston)
#scale dataset and make data frame
boston_scaled1<-as.data.frame(scale(Boston))
dist_eu <-dist(boston_scaled1)
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4620 4.8240 4.9110 6.1860 14.4000
Now we apply K-means to the dataset. K-means calculates the distances and assigns observations to clusters. We start with a randomly selected number of 4 cluster centers.
km <- kmeans(boston_scaled1, centers = 4)
However, we want to determine the optimal number of clusters. That can be done with the behaviour of the total of within cluster sum of squares (WCSS) when the number of clusters changes. The optimal number of clusters is when the total WCSS drops radically. We are setting the maximal amount of clusters to be 10. In the visualization we can see that the WCSS drops radically between one and two. Therefor two would be the optimal amount of clusters.
set.seed(123)
#set the max number of clusters to be ten
k_max<- 10
#calculate total WCSS
twcss <- sapply(1:k_max, function(k){kmeans(Boston, k)$tot.withinss})
#visualizing WCSS
qplot(x = 1:k_max, y = twcss, geom = 'line')
We run the K-means algorythm again with two cluster centres. The results are visualized in a plot matric with all the results and then exemplarily zoomed in for the five variables rm, age, dis, rad and tax.The two clusters can be seen in red and black and how they relate for each combination of variables.
km <- kmeans(boston_scaled1, centers = 2)
#visualize Kmeans
pairs(boston_scaled1, col = km$cluster)
pairs(boston_scaled1[6:10], col = km$cluster)
At first we scale the Boston dataset again.
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
boston_scaled2 <-scale(Boston)
summary(boston_scaled2)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
Now we perform the K-means on the standardized dataset.
km2 <- kmeans(boston_scaled2, center = 3)
boston_scaled2 <- as.data.frame(boston_scaled2)
Finally we perform Linear Discriminant Analysis, using the clusters as target classes, including all the variables from the Boston data in the LDA model.
lda.fit2 <- lda(km2$cluster~., data = boston_scaled2)
Visualizing the results, we can see wich ones are the most influential variables seperating the clusters:rad, nox and zn.
# function for the lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# setting target classes as numeric
classes <- as.numeric(km2$cluster)
# plotting the lda results
plot(lda.fit2, dimen = 2, col=classes, pch= classes)
lda.arrows(lda.fit, myscale = 1)
We are running the code bellow for the scaled train data that we used to fit the LDA.It creates a matrix product, which is a projection of the data points.
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
Now we are installing and accessing the plotly package in order to create a 3D plot from our data.
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
We draw the same plot again, but set the crime classes to be the colours.
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = train$crime)
Drawing the same plot again with the colours matching the clusters of the K-means.
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = train$cl)